import { Form, Row, Col, Tabs, Radio, Select, Input, Card, Checkbox } from 'antd';
import { addon } from "pao-aop";
import { reactControl, ReactView, ReactViewControl, ReactViewState } from "pao-aop-client";
import React from "react";
import SignFrameLayout, { InputType as inputType } from "src/business/components/buss-components/sign-frame-layout";
import { MainContent } from "src/business/components/style-components/main-content";
import { request_func } from "src/business/util_tool";
import { AppServiceUtility } from "src/projects/app/appService";
import { ROUTE_PATH } from "src/projects/router";
import TextArea from 'antd/lib/input/TextArea';
import { MainCard } from "src/business/components/style-components/main-card";
import { UserEntry } from "src/projects/components/user-entry";
import { FileUploadBtn } from "src/business/components/buss-components/file-operation-btn/file-upload-btn";
import { remote } from "src/projects/remote";
import { beforeUpload } from "src/projects/app/util-tool";
import moment from 'moment';
let { Option } = Select;
const { TabPane } = Tabs;

export interface ServiceItemPackageFormValues {
    id?: string;
}
/**
 * 组件：预约入院视图控件状态
 */
export interface CheckInDetailViewState extends ReactViewState {
    loading?: boolean;
    bed_number?: any;
    /** 长者id */
    user?: any;
    /** 项目列表 */
    item_list?: any[];
    /** 项目列表集合 */
    all_item_list?: any[];
    /** 服务包数据 */
    /** 基础数据 */
    base_data?: {};
    /** 组织机构 */
    organizational?: any[];
    /** 床位 */
    bed_list?: any[];
    /** 床位名称 */
    bed_name: string;
    /** 床位id */
    bed_id: string;
    /** 订单id */
    order_id: string;

}

/**
 * 组件：预约入院视图控件
 * 描述
 */
export class CheckInDetailView extends ReactView<CheckInDetailViewControl, CheckInDetailViewState> {
    constructor(props: CheckInDetailViewControl) {
        super(props);
        this.state = {
            loading: false,
            bed_number: [],
            user: {},
            item_list: [],
            all_item_list: [],
            base_data: {},
            bed_list: [],
            bed_name: '',
            bed_id: '',
            order_id: ''
        };
    }
    /** 查看住宿详情 */
    onAccommodationIconClick = (type: string, contents: any) => {
        if ('icon_edit' === type) {
            this.props.history!.push(ROUTE_PATH.leaveInsert + '/' + contents.id);
        }
    }
    /** 查看评估详情 */
    onIconEvaluationClick = (type: string, contents: any) => {
        if ('icon_edit' === type) {
            this.props.history!.push(ROUTE_PATH.changeAssessmentProject + '/' + contents.id);
        }
    }
    /** 提交方法 */
    handleSubmit = (e: any) => {
        e.preventDefault();
        const { form } = this.props;
        form!.validateFields((err: Error, values: ServiceItemPackageFormValues) => {
            let formValue = {};
            let service_item: any = [];
            this.state.all_item_list!.map(() => {
                service_item.push({});
            });
            for (let key in values) {
                if (key.indexOf('___') !== -1) {
                    let keys = key.split('___');
                    service_item[parseInt(keys[1], undefined)][keys[0]] = values[key];
                } else {
                    formValue[key] = values[key];
                }
            }
            formValue['service_item'] = service_item;
            AppServiceUtility.service_item_package.update_service_item_package!(formValue)!
                .then((data) => {
                    if (data) {
                        this.props.history!.push(ROUTE_PATH.serviceItemPackage);
                    }
                });
        });
    }
    /** 返回按钮 */
    retBtn = () => {
        this.props.history!.push(ROUTE_PATH.serviceItemPackage);
    }
    /** 添加项目按钮 */
    componentDidMount() {
        // 获取入住详情
        let key = this.props.match!.params.key;
        let user_id = key.indexOf('form') > 0 ? key.split('form=')[0] : key;
        let url = key.indexOf('form') > 0 ? key.split('form=')[1] : 'get_check_in_list_all';
        const param = [{ user_id }, 1, 1];
        // 获取入住详情
        request_func(this, AppServiceUtility.check_in_service![url], param, (data: any) => {
            let bed_number: any = [];
            const result: any = data.result[0] ? data.result[0] : {};
            const date_birth = result.user.personnel_info.date_birth;
            result.user.personnel_info.date_birth = moment(date_birth);
            const select_product = result.order.detail;
            this.setState({ bed_number, user: result.user, bed_name: result.bed.name, bed_id: result.bed.id });
            // 获取服务包
            request_func(this, AppServiceUtility.services_project_service.get_all_item_from_product, [{ 'id': result.bed.service_item_package_id }], (data: any) => {
                let all_product = data.result;
                // const name = ['实际发生天数', '总天数', '房间人数', '总升数'];
                for (var i = 0; i < all_product.length; i++) {
                    for (var j = 0; j < select_product.length; j++) {
                        if (all_product[i].product_id === select_product[j].product_id) {
                            const service_option = select_product[j].service_option;
                            let all_service_option = all_product[i].service_option;
                            for (var x = 0; x < service_option.length; x++) {
                                if (service_option[x].option_type === 'service_before') {
                                    for (var y = 0; y < all_service_option.length; y++) {
                                        if (service_option[x].name === all_service_option[y].name) {
                                            all_product[i].service_option[y].option_value = service_option[x].option_value;
                                        } else {
                                            delete all_product[i].service_option[y];
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                this.setState({
                    all_item_list: all_product,
                });
            });
            request_func(this, AppServiceUtility.service_item_package.get_service_item_package, [{ id: result.bed.service_item_package_id }], (data: any) => {
                this.setState({
                    base_data: data!.result![0],
                });
            });
        });
    }
    handleSubmitService = (e: any) => {

    }
    render() {

        // 住宿记录
        const columns_data_source = [{
            title: '床位编号',
            dataIndex: 'bed_number',
            key: 'bed_number',
        }, {
            title: '入住时间',
            dataIndex: 'checkin_date',
            key: 'checkin_date',
        }, {
            title: '离开时间',
            dataIndex: 'checkout_date',
            key: 'checkout_date',
        }, {
            title: '记录说明',
            dataIndex: 'record',
            key: 'record',
        }, {
            title: '申请时间',
            dataIndex: 'apply_date',
            key: 'apply_date',
        }];
        // 住宿记录
        const accommodation = {
            loading: this.state.loading,
            type_show: false,
            edit_form_items_props: [
                {
                    type: inputType.select,
                    label: "床位编号",
                    decorator_id: "bed_number",
                    option: {
                        placeholder: '请选择床位编号',
                        childrens: this.state.bed_number
                    }
                }, {
                    type: inputType.date,
                    label: "申请时间",
                    decorator_id: "apply_date"
                },

            ],
            columns_data_source: columns_data_source,
            on_icon_click: this.onAccommodationIconClick,
            service_object: AppServiceUtility.leaveRecord_service,
            service_option: {
                select: {
                    service_func: 'get_leave_list_all',
                    service_condition: [{ residents_id: this.state.user.id }, 1, 10]
                },
                delete: {
                    service_func: 'del_leave_record',
                }
            },
        };
        // // 评估记录
        const columns_data_evaluation = [{
            title: '评估名称',
            dataIndex: 'template_name',
            key: 'template_name',
        }, {
            title: '评估类型',
            dataIndex: 'template_type',
            key: 'template_type',
        }, {
            title: '评估意见',
            dataIndex: 'assessment_opinions',
            key: 'assessment_opinions',
        }, {
            title: '评估得分',
            dataIndex: 'total_score',
            key: 'total_score',
        }, {
            title: '评估时间',
            dataIndex: 'modify_date',
            key: 'modify_date',
        }];
        const evaluation = {
            loading: this.state.loading,
            type_show: false,
            edit_form_items_props: [
                {
                    type: inputType.input,
                    label: "评估名称",
                    decorator_id: "template_name",
                    option: {
                        placeholder: '请选择评估名称',
                        childrens: this.state.bed_number
                    }
                }, {
                    type: inputType.select,
                    label: "评估类型",
                    decorator_id: "template_type",
                    option: {
                        placeholder: '请选择评估类型',
                        childrens: []
                    }
                },
                {
                    type: inputType.date,
                    label: "评估时间",
                    decorator_id: "create_date",
                },

            ],
            columns_data_source: columns_data_evaluation,
            on_icon_click: this.onIconEvaluationClick,
            service_object: AppServiceUtility.competence_assessment_service,
            service_option: {
                select: {
                    service_func: 'get_competence_assessment_list_all',
                    service_condition: [{ elder: this.state.user.id }, 1, 10]
                },
                delete: {
                    service_func: 'delete_competence_assessment'
                }
            },
        };

        // 服务产品
        // 如果服务项目不为空则生成
        const formItemLayout_service = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 5 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 },
            },
        };
        const { getFieldDecorator } = this.props.form!;
        let item_list;
        if (this.state.all_item_list && this.state.all_item_list!.length > 0) {
            item_list = this.state.all_item_list!.map((value, index) => {
                return (
                    <Card key={index}>
                        <Row type="flex" justify="center">
                            <Col span={12}>
                                <Form.Item label='服务产品'>
                                    {getFieldDecorator('service_item___' + index, {
                                        initialValue: value.product_name ? value.product_name : '',
                                        rules: [{
                                            message: '请选择服务产品'
                                        }],
                                    })(
                                        <Input disabled={true} />
                                    )}
                                </Form.Item>
                                {
                                    value.valuation_formula ? (
                                        <Form.Item label='计价方式'>
                                            {getFieldDecorator('valuation_formula___' + '0', {
                                                initialValue: value.valuation_formula ? value.valuation_formula[0].name : "",
                                                rules: [{
                                                    required: false,
                                                    message: '请选择计价方式'
                                                }],
                                                option: {
                                                    disabled: true,
                                                    placeholder: '请选择计价方式'
                                                }
                                            })(
                                                <Input disabled={true} />
                                            )}
                                        </Form.Item>
                                    ) : ''
                                }
                                {
                                    value.type_name ? (
                                        <Form.Item label='服务类型'>
                                            {getFieldDecorator('service_type___' + 0, {
                                                initialValue: value.item_type ? value.item_type : "",
                                                rules: [{
                                                    required: false,
                                                }],
                                                option: {
                                                    disabled: true
                                                }
                                            })(
                                                <Select disabled={true}>
                                                    <Option key={value.item_type} >{value.type_name}</Option>
                                                </Select>
                                            )}
                                        </Form.Item>
                                    ) : ''
                                }
                                {(() => {
                                    if (!value.service_option) {
                                        return null;
                                    }
                                    return value.service_option.map((service_option: any, indexs: any) => {
                                        if (service_option.option_type === 'service_after') {
                                            return (
                                                <Row style={{ display: 'none' }}>
                                                    <Form.Item label={service_option.name} key={indexs}>
                                                        {getFieldDecorator(value.product_id + '___' + service_option.name + '___' + service_option.option_type, {
                                                            initialValue: service_option.option_value || (service_option.default_value || ''),
                                                            rules: [{
                                                                required: false,
                                                            }],
                                                        })(
                                                            <Input type="hidden" />
                                                        )}
                                                    </Form.Item>
                                                </Row>
                                            );
                                        }
                                        if (service_option.option_value_type === '1') {
                                            return (
                                                <Form.Item label={service_option.name} key={indexs}>
                                                    {getFieldDecorator(value.product_id + '___' + service_option.name + '___' + service_option.option_type, {
                                                        initialValue: service_option.option_value || (service_option.default_value || ''),
                                                        rules: [{
                                                            required: false,
                                                        }],
                                                    })(
                                                        <Radio.Group>
                                                            {
                                                                service_option.option_content!.map((item: any, content: any) => {
                                                                    return <Radio key={content} value={item.option_value}>{item.option_content}</Radio>;
                                                                })
                                                            }
                                                        </Radio.Group>
                                                    )}
                                                </Form.Item>
                                            );
                                        } else if (service_option.option_value_type === '2') {
                                            return (
                                                <Form.Item label={service_option.name} key={indexs}>
                                                    {getFieldDecorator(value.product_id + '___' + service_option.name + '___' + service_option.option_type, {
                                                        initialValue: service_option.option_value || (service_option.default_value || ''),
                                                        rules: [{
                                                            required: false,
                                                        }],
                                                    })(
                                                        <Checkbox.Group>
                                                            {
                                                                service_option.option_content!.map((item: any, idx: any) => {
                                                                    return <Checkbox key={idx} value={item.option_value}>{item.option_content}</Checkbox>;
                                                                })
                                                            }
                                                        </Checkbox.Group>
                                                    )}
                                                </Form.Item>
                                            );
                                        } else if (service_option.option_value_type === '3') {
                                            return (
                                                <Form.Item label={service_option.name} key={indexs}>
                                                    {getFieldDecorator(value.product_id + '___' + service_option.name + '___' + service_option.option_type, {
                                                        initialValue: service_option.option_value || (service_option.default_value || ''),
                                                        rules: [{
                                                            required: false,
                                                        }],
                                                    })(
                                                        <Input disabled={true} />
                                                    )}
                                                </Form.Item>
                                            );
                                        } else {
                                            return null;
                                        }
                                    });
                                })()}
                                {
                                    // value.service_option ? value.service_option.map((service_options: any, indexs: any) => {
                                    //     return service_options.option_type  ? (
                                    //         <Form.Item label={service_options.name} key={indexs}>
                                    //             {getFieldDecorator(value.product_id + '___' + indexs, {
                                    //                 initialValue: service_options.value ? service_options.value : '',
                                    //                 rules: [{
                                    //                     required: false,
                                    //                 }],
                                    //             })(
                                    //                 <Radio.Group>
                                    //                     {
                                    //                         service_options.option_content ? service_options.option_content!.map((item: any, content: any) => {
                                    //                             return <Radio key={content} value={service_options.name + '___' + item.option_value + '___' + service_options.option_type}>{item.option_content}</Radio>;
                                    //                         }) : <Radio key={0} value={service_options.name + '___' + service_options.default_value + '___' + service_options.option_type}>{service_options.default_value}</Radio>
                                    //                     }
                                    //                 </Radio.Group>
                                    //             )}
                                    //         </Form.Item>
                                    //     ) : '';
                                    // }) : ''
                                }
                            </Col>
                        </Row>
                    </Card >
                );
            });
        }
        // Object.assign(accommodation, table_param);
        // Object.assign(elder_info, edit_props);
        // Object.assign(evaluation, table_param);
        return (
            <Tabs defaultActiveKey="1" >
                <TabPane tab="长者信息" key="1">
                    <MainContent>
                        <UserEntry base_info={this.state.user ? this.state.user : {}} is_detailed_info={false} />
                    </MainContent>
                </TabPane>
                <TabPane tab="住宿记录" key="2">
                    <SignFrameLayout {...accommodation} />
                </TabPane>

                <TabPane tab="评估记录" key="3">
                    <SignFrameLayout {...evaluation} />
                </TabPane>
                <TabPane tab="服务产品" key="4">
                    <MainContent>
                        <Form {...formItemLayout_service} onSubmit={this.handleSubmitService}>
                            <MainCard title='服务产品'>
                                <Row type="flex" justify="center">
                                    <Col span={12}>
                                        <Form.Item label='床位'>
                                            {getFieldDecorator('service_item_package_id', {
                                                initialValue: this.state.bed_name ? this.state.bed_name : '',
                                                rules: [{
                                                    required: false,
                                                    message: '请选择床位'
                                                }],
                                            })(
                                                <Input disabled={true} />
                                            )}
                                        </Form.Item>

                                        <Form.Item label='服务产品名称'>
                                            {getFieldDecorator('name', {
                                                initialValue: this.state.base_data ? this.state.base_data['name'] : '',
                                            })(
                                                <Input disabled={true} />
                                            )}
                                        </Form.Item>
                                        <Form.Item label='是否启用'>
                                            {getFieldDecorator('state', {
                                                initialValue: this.state.base_data ? this.state.base_data['state'] : [],
                                            })(
                                                <Radio.Group disabled={true}>
                                                    <Radio value={1}>启用</Radio>
                                                    <Radio value={0}>停用</Radio>
                                                </Radio.Group>
                                            )}
                                        </Form.Item>
                                        <Form.Item label='所属组织机构'>
                                            {getFieldDecorator('org_id', {
                                                initialValue: this.state.base_data ? this.state.base_data['organizational_name'] : '',
                                            })(
                                                <Input disabled={true} />
                                            )}
                                        </Form.Item>
                                        <Form.Item label='服务包图片'>
                                            {getFieldDecorator('picture_collection', {
                                                initialValue: this.state.base_data!['picture_collection'] ? this.state.base_data!['picture_collection'] : '',
                                            })(
                                                <FileUploadBtn list_type={"picture-card"} contents={"plus"} action={remote.upload_url} beforeUpload={beforeUpload} upload_amount={-1} />
                                            )}
                                        </Form.Item>
                                        <Form.Item label='附加合同条款'>
                                            {getFieldDecorator('additonal_contract_terms', {
                                                initialValue: this.state.base_data ? this.state.base_data['additonal_contract_terms'] : '',
                                            })(
                                                <TextArea rows={4} disabled={true} />
                                            )}
                                        </Form.Item>
                                        <Form.Item label='服务产品介绍'>
                                            {getFieldDecorator('service_product_introduce', {
                                                initialValue: this.state.base_data ? this.state.base_data['service_product_introduce'] : '',
                                            })(
                                                <TextArea rows={4} disabled={true} />
                                            )}
                                        </Form.Item>
                                        <Form.Item label='是否服务项目'>
                                            {getFieldDecorator('is_service_item', {
                                                initialValue: this.state.base_data!['is_service_item'] ? this.state.base_data!['is_service_item'] : '',
                                            })(
                                                <Select showSearch={true} disabled={true}>
                                                    <Option value="true">是</Option>
                                                    <Option value="false">否</Option>
                                                </Select>
                                            )}
                                        </Form.Item>
                                    </Col>
                                </Row>
                            </MainCard>
                            <MainCard title='服务项目清单'>
                                {item_list}
                            </MainCard>
                        </Form>
                    </MainContent>
                </TabPane>
            </Tabs>

        );
    }
}

/**
 * 控件：预约入院视图控件
 * 描述
 */
@addon('CheckInDetailView', '预约登记视图控件', '描述')
@reactControl(Form.create<any>()(CheckInDetailView), true)
export class CheckInDetailViewControl extends ReactViewControl {
    constructor() {
        super();
    }
}